#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class BeijingshiQuPolicy(BaseTaxPolicySpider):
    name = 'beijingshi_qu_policy'

    province = '北京市'
    city = '北京市'
    park = ''
    url = ''

    custom_settings = {
        "DEFAULT_REQUEST_HEADERS": {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh,en;q=0.9,zh-CN;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Pragma": "no-cache",
            "Sec-Fetch-Dest": "document",
            "Sec-Fetch-Mode": "navigate",
            "Sec-Fetch-Site": "none",
            "Sec-Fetch-User": "?1",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
            "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        }
    }

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['北京市东城区人民政府', '东城区', 'https://www.bjdch.gov.cn/zwgk/zcwj2024/index.html'],
            ['北京市朝阳区人民政府', '朝阳区', 'http://www.bjchy.gov.cn/affair/file/qzffile/index.html'],
            ['北京市朝阳区人民政府', '朝阳区', 'http://www.bjchy.gov.cn/affair/file/qzbfile/index.html'],
            ['北京市朝阳区人民政府', '朝阳区', 'http://www.bjchy.gov.cn/affair/file/otherfile/index.html'],
            ['北京市门头沟区人民政府', '门头沟区', 'https://www.bjmtg.gov.cn/bjmtg/zwgk/zcwj/wjlx/qzfwj/index.shtml'],
            ['北京市门头沟区人民政府', '门头沟区', 'https://www.bjmtg.gov.cn/bjmtg/zwgk/zcwj/wjlx/qzfbwj/index.shtml'],
            ['北京市门头沟区人民政府', '门头沟区', 'https://www.bjmtg.gov.cn/bjmtg/zwgk/zcwj/dzjg/qgbm/index.shtml'],
            ['北京市丰台区人民政府', '丰台区', 'http://www.bjft.gov.cn/ftq/ftzcwj/zczlmlist.shtml'],
            ['北京市通州区人民政府', '通州区', 'https://www.bjtzh.gov.cn/bjtz/xxfb/zfwj/index.shtml'],
            ['北京市通州区人民政府', '通州区', 'https://www.bjtzh.gov.cn/bjtz/xxfb/zfbwj/index.shtml'],
            ['北京市通州区人民政府', '通州区', 'https://www.bjtzh.gov.cn/bjtz/xxfb/bmwj/index.shtml'],
            ['北京市怀柔区人民政府', '怀柔区', 'https://www.bjhr.gov.cn/zwgk/zcwj/qzfwj/index.html'],
            ['北京市怀柔区人民政府', '怀柔区', 'https://www.bjhr.gov.cn/zwgk/zcwj/qzfbgswj/index.html'],
            ['北京市怀柔区人民政府', '怀柔区', 'https://www.bjhr.gov.cn/zwgk/zcwj/gbmwj/index.html'],
            ['北京市怀柔区人民政府', '怀柔区', 'https://www.bjhr.gov.cn/zwgk/zcwj/gfxwj/index.html'],
            ['北京市密云区人民政府', '密云区', 'https://www.bjmy.gov.cn/zwgk/zcwj/qzfwj/index.html'],
            ['北京市密云区人民政府', '密云区', 'https://www.bjmy.gov.cn/zwgk/zcwj/qzfbwj/index.html'],
            ['北京市密云区人民政府', '密云区', 'https://www.bjmy.gov.cn/zwgk/zcwj/xzgfxwj/index.html'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        # print(response.url)
        prev_item = response.meta.get('item')
        if '系统繁忙,请稍后点击' in response.text:
            yield scrapy.Request(response.url, callback=self.parse_list, dont_filter=True,
                                 meta={'item': prev_item, 'is_next': False})
        elem_list = response.xpath(
            "//*[@class='zcfb_r_box_list' or @class='list line5 mt20' or @class='lm_lbsa']//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//*[@class='lmgglis' or @class='m-ulList' or @class='hr_ls_li']//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//*[@class='list' or @class='middle_result_con']//div//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::div[string-length(string(.))>=9]")
        print(len(elem_list), response.url)
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jsp' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            # print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下页' in response.text or '下一页' in response.text or '>' in response.text:
                totalpage = response.xpath(""".""").re_first(r"var\s*countPage\s*=\s*(\d+)") or \
                            response.xpath(""".""").re_first(r"var\s*_nPageCount\s*=\s*(\d+)") or \
                            response.xpath(""".""").re_first(r"共(\d+)页") or \
                            response.xpath(""".""").re_first(r"createPageHTML\('page_div',(\d+)") or \
                            response.xpath(""".""").re_first(r"Pager\(\{size\:\s*(\d+)") or \
                            response.xpath(""".""").re_first(r",this,'(\d+)")
                print('totalpage', totalpage, response.url)
                if totalpage and int(totalpage) > 1:
                    for page in range(1, int(totalpage) + 1):
                        url = response.url.replace('index.', f'index_{page}.').replace('zczlmlist.', f'zczlmlist_{page}.')
                        if 'index' not in url and 'zczlmlist' not in url:
                            url = f'index_{page}.html'
                        yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
                else:
                    print(response.url)
            else:
                print(response.url)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()[:10] or response.xpath(
            """string(//meta[@name='firstpublishedtime']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl beijingshi_qu_policy".split())
